﻿Public Class CreerDocument
    Inherits OpenDelibPage

    Private pSelectionFichier As Boolean
    Private pCheminFichier As String
    Public Property ModeFiche As Tools.ModeFiche
        Get
            Return CType(ViewState("mode_fiche"), Tools.ModeFiche)
        End Get
        Private Set(value As Tools.ModeFiche)
            ViewState("mode_fiche") = value
        End Set
    End Property
    Public Property CleEntite As Integer
        Get
            Return CType(ViewState("cle_entite"), Integer)
        End Get
        Protected Set(value As Integer)
            ViewState("cle_entite") = value
        End Set
    End Property
    Public Property Entite As ServiceDocuments.Document
        Get
            Return CType(ViewState("entite"), ServiceDocuments.Document)
        End Get
        Protected Set(value As ServiceDocuments.Document)
            ViewState("entite") = value
        End Set
    End Property
    Public Property Chrono As String
        Get
            Return CStr(ViewState("chrono"))
        End Get
        Set(value As String)
            ViewState("chrono") = value
        End Set
    End Property


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Odyssee.WebControles.JQPopupPanel.SetCancelScript(Me.btnAnnuler, False)

        If Not IsPostBack Then
            ' Lecture des paramètres
            Me.ModeFiche = CType(Request.QueryString("modeFiche"), Tools.ModeFiche)
            Me.CleEntite = Nothing

            If Me.ModeFiche = Tools.ModeFiche.Modification Then
                Dim cle As String = Server.UrlDecode(Request.QueryString("cle"))
                If Not IsNumeric(cle) OrElse CInt(cle) <= 0 Then
                    Me.ModeFiche = Tools.ModeFiche.Creation
                Else
                    Me.CleEntite = CInt(cle)
                    ' Chargement de l'entite
                    Using svc As New ServiceDocuments.DocumentsClient
                        Dim criteres As ServiceDocuments.CriteresRechercheDocument = New ServiceDocuments.CriteresRechercheDocument
                        criteres.Authentication = New ServiceDocuments.AuthenticationParameters
                        criteres.Authentication.Token = Tools.GetInstance().getToken()
                        criteres.Cle = Me.CleEntite

                        Try
                            Dim result As ServiceDocuments.ResultatRechercheDocument = svc.Recherche(criteres)

                            If result.Documents IsNot Nothing AndAlso result.OK Then
                                If result.Documents.Count <= 0 Then
                                    NotifyErreur("Le document n°" & CleEntite.ToString & "' est introuvable !")
                                    Me.ModeFiche = Tools.ModeFiche.Creation
                                    Me.CleEntite = Nothing
                                Else
                                    Me.Entite = result.Documents(0)
                                End If
                            Else
                                NotifyErreur(result.ErrorMessage)
                                Me.ModeFiche = Tools.ModeFiche.Creation
                                Me.CleEntite = Nothing
                            End If
                        Catch ex As Exception
                            NotifyErreur(ex.Message)
                            Me.ModeFiche = Tools.ModeFiche.Creation
                            Me.CleEntite = Nothing
                        End Try
                    End Using
                End If
            End If
        End If

        pSelectionFichier = False
        If Me.ModeFiche = Tools.ModeFiche.Creation Then
            If IsNumeric(Request.QueryString("selectionFichier")) AndAlso CInt(Request.QueryString("selectionFichier")) = 1 Then
                pSelectionFichier = True
                pCheminFichier = ""
            ElseIf String.IsNullOrEmpty(Request.QueryString("fichier")) Then
                NotifyErreur("Le fichier est obligatoire !")
                Return
            Else
                pSelectionFichier = False
                pCheminFichier = Request.PhysicalApplicationPath & "Temp\" & Tools.GetInstance.getToken & "\" & HttpUtility.UrlDecode(Request.QueryString("fichier"))
            End If

        End If

        Me.divSelectionFichier.Visible = pSelectionFichier
        If pSelectionFichier Then
            Dim t As New PostBackTrigger()
            t.ControlID = Me.btnOK.ID
            Me.upMain.Triggers.Add(t)
        End If

        If Not IsPostBack Then

            ' Lecture du chrono
            Using svc As New ServiceParametre.ParametresClient
                Dim params As New ServiceParametre.OperationParameters
                params.Authentication = New ServiceParametre.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken

                Dim results As ServiceParametre.OIItemResult = Nothing
                Try
                    results = svc.GetChronoEnCours(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de lire le chrono en cours" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return
                    Else
                        Me.Chrono = results.Item.Code
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                End Try
            End Using

            ' Chargement des types et états de document
            Using svc As New ServiceParametre.ParametresClient
                Dim params As New ServiceParametre.ListeParametreParameters
                params.Authentication = New ServiceParametre.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken

                ' Types
                params.EntiteParametrage = 27
                Dim results As ServiceParametre.OIItemListResult = Nothing
                Try
                    results = svc.ListeParametre(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de charger les types de documents" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return
                    Else
                        Me.cmbType.Items.Add(New ListItem("", ""))
                        For Each item As ServiceParametre.OIItem In results.Liste
                            Me.cmbType.Items.Add(New ListItem(item.Libelle, item.Code))
                        Next
                        If Me.cmbType.Items.Count > 0 Then Me.cmbType.SelectedIndex = 0
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                End Try

                ' Etats
                params.EntiteParametrage = 29
                results = Nothing
                Try
                    results = svc.ListeParametre(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de charger les états de documents" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return
                    Else
                        Me.cmbEtat.Items.Add(New ListItem("", ""))
                        For Each item As ServiceParametre.OIItem In results.Liste
                            Me.cmbEtat.Items.Add(New ListItem(item.Libelle, item.Code))
                        Next
                        Me.cmbEtat.SelectedIndex = 0
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                End Try
            End Using

            Select Case Me.ModeFiche
                Case Tools.ModeFiche.Creation
                    divNature.Visible = False
                    divOrigine.Visible = False

                    ' Ajout de l'objet
                    If Not pSelectionFichier AndAlso pCheminFichier <> "" Then
                        Me.txtObjet.Text = IO.Path.GetFileName(pCheminFichier)
                    End If

                Case Tools.ModeFiche.Modification
                    divNature.Visible = True
                    divOrigine.Visible = True
                    Me.txtObjet.Text = Me.Entite.Objet1
                    Me.cmbType.SelectedValue = Me.Entite.Type
                    Me.cmbEtat.SelectedValue = Me.Entite.Etat
                    Me.txtNature.Text = Me.Entite.LibelleNature
                    Me.txtOrigine.Text = Me.Entite.LibelleOrigine

            End Select

        End If

        If pSelectionFichier Then
            SetFocus(Me.cheminFichier)
        Else
            SetFocus(Me.txtObjet)
        End If
    End Sub

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        Dim nature As Integer

        ' Validation des champs
        If pSelectionFichier AndAlso cheminFichier.FileName = "" Then
            NotifyErreur("Fichier obligatoire !")
            Return
        End If

        If txtObjet.Text = "" Then
            NotifyErreur("Objet obligatoire !")
            Return
        End If

        If cmbType.SelectedValue = "" Then
            NotifyErreur("Type obligatoire !")
            Return
        End If



        If Me.ModeFiche = Tools.ModeFiche.Creation Then
            ' Upload et sauvegarde du fichier sur le serveur dans un dossier temp
            If pSelectionFichier Then
                pCheminFichier = Request.PhysicalApplicationPath & "Temp\" & Tools.GetInstance.getToken
                If Not IO.Directory.Exists(pCheminFichier) Then IO.Directory.CreateDirectory(pCheminFichier)
                pCheminFichier &= "\" & System.IO.Path.GetFileName(cheminFichier.PostedFile.FileName)
                cheminFichier.PostedFile.SaveAs(pCheminFichier)
            End If

            ' Conversion du document en Base64
            Dim nomTempFile As String = System.IO.Path.GetRandomFileName
            Dim b() As Byte = IO.File.ReadAllBytes(pCheminFichier)
            Dim docBase64 As String = Convert.ToBase64String(b)

            ' Suppression du fichier sur le serveur dans un dossier temp
            If pSelectionFichier Then
                IO.File.Delete(pCheminFichier)
            End If

            ' Lecture de la nature du document
            Using svc As New ServiceDocuments.DocumentsClient
                Dim params As New ServiceDocuments.ParametresNatureDocument
                params.Authentication = New ServiceDocuments.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken
                params.NomFichier = IO.Path.GetFileName(pCheminFichier)

                Dim results As ServiceDocuments.ResultatNatureDocument = Nothing
                Try
                    results = svc.NatureSelonNomFichier(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de déterminer la nature du fichier '" & IO.Path.GetFileName(pCheminFichier) & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return
                    Else
                        nature = results.Nature
                    End If
                Catch ex As Exception
                    NotifyErreur(ex.Message)
                End Try
            End Using

            Me.Entite = New ServiceDocuments.Document
            Me.Entite.Chrono = Me.Chrono
            Me.Entite.ContenuFichierBase64 = docBase64
            Me.Entite.DateEmission = Now.Date
            Me.Entite.ExtensionOrigine = IO.Path.GetExtension(pCheminFichier)
            Me.Entite.FichierOrigine = IO.Path.GetFileName(pCheminFichier)
            Me.Entite.Nature = nature
            Me.Entite.Origine = Asc("I")
        End If

        Me.Entite.Objet1 = Me.txtObjet.Text
        Me.Entite.Type = Me.cmbType.SelectedValue
        Me.Entite.Etat = Me.cmbEtat.SelectedValue
        If Me.Entite.ZoneSup Is Nothing Then Me.Entite.ZoneSup = New ServiceDocuments.ZoneSup()


        ' Création ou mise à jour du document
        Using svc As New ServiceDocuments.DocumentsClient
            Dim params As New ServiceDocuments.ParametresCreationDocument
            params.Authentication = New ServiceDocuments.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Document = Me.Entite

            Try
                If Me.ModeFiche = Tools.ModeFiche.Creation Then
                    Dim results As ServiceDocuments.ResultatCreationDocument = Nothing
                    results = svc.Creation(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de créer le document" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return
                    Else
                        Me.CleEntite = results.Cle
                    End If
                Else
                    Dim results As ServiceDocuments.OperationResult = Nothing
                    results = svc.MiseAJour(params)
                    If results Is Nothing OrElse Not results.OK Then
                        NotifyErreur("Impossible de mettre à jour le document" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                        Return
                    End If
                End If



            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return
            End Try
        End Using

        ScriptManager.RegisterStartupScript(Me, Me.GetType, "FermeturePopup", Odyssee.WebControles.JQPopupPanel.CreateOKScript(Me.CleEntite.ToString), True)
    End Sub
End Class